#!/usr/bin/env python

from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import formatdate
from email import Encoders
import os
import smtplib
import sys
 
# http://www.pastequestion.com/blog/python/send-email-with-attachments-using-python.html

def sendmail(host, from_address, to_address, password, subject=None, message=None, attach_files=None):
    smtp = smtplib.SMTP()
    smtp.connect(host)
    smtp.ehlo()
    smtp.starttls()
    smtp.login(from_address, password)
    m_message = encode_message(from_address, to_address, subject, message, attach_files)
    result = smtp.sendmail(from_address, to_address, m_message.as_string())
    smtp.quit()
    return result

def encode_message(from_address, to_address, subject=None, message=None, attach_files=None):
    m_message = MIMEMultipart()
    m_message['from'] = from_address
    m_message['to'] = ",".join(to_address)
    m_message['date'] = formatdate(localtime=True)
    if subject:
        m_message['subject'] = subject
    m_message['x-mailer'] = "Python X-Mailer"
    if message:
        m_message.attach(MIMEText(message, "text/plain", "UTF-8"))
    if attach_files:
        print attach_files
        for file in attach_files:
            if os.path.exists(file):
                part = MIMEBase("application", "octet-stream")
                part.set_payload(open(file, "rb").read())
                Encoders.encode_base64(part)
                part.add_header("content-disposition", "attachment", filename=os.path.basename(file))
                m_message.attach(part)
    return m_message

def main():
    from_address = raw_input("from: ")
    user, domain = from_address.split("@")
    if domain == "usc.edu":
        host = "email.usc.edu"
    elif domain == "hotmail.com" or domain == "live.com" or domain == "msn.com":
        host = "smtp.live.com"
    else:
        host = raw_input("SMTP server: ")
    password = raw_input("password: ")
    to_address = raw_input("to(s): ").split()
    subject = raw_input("subject: ")
    message = raw_input("message: ")
    if len(sys.argv) > 1: # Attachment files
        total_size = 0
        count = 1
        files = []
        limit = 10*(2**20) # 10M
        for file in sys.argv[1:]:
            size = os.path.getsize(file)
            if size > limit:
                print "size of %s is over, skipped" % (file)
                continue
            if total_size + size > limit:
                sendmail(host, from_address, to_address, password, "%s #%s" % (subject, count), message, files)
                total_size = 0
                count += 1
                files = []
            total_size += size
            files.append(file)
        if files:
            sendmail(host, from_address, to_address, password, "%s #%s" % (subject, count), message, files)
    else:
        sendmail(host, from_address, to_address, password, subject, message)

if __name__ == "__main__":
    main()

